package com.jet.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jet.core.utils.IdUtil;
import com.jet.member.domain.dto.MemberLevelDto;
import com.jet.member.domain.dto.MemberLevelItemDto;
import com.jet.member.domain.entity.MemberLevel;
import com.jet.member.mapper.MemberLevelMapper;
import com.jet.member.service.IMemberLevelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jet.member.service.IMemberService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-02
 */
@Service
public class MemberLevelServiceImpl extends ServiceImpl<MemberLevelMapper, MemberLevel> implements IMemberLevelService {

    private final IMemberService memberService;

    public MemberLevelServiceImpl(IMemberService memberService) {
        this.memberService = memberService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchEdit(long merchantNo, MemberLevelDto dto) {
        Wrapper<MemberLevel> wrapper = new LambdaQueryWrapper<MemberLevel>()
                .eq(MemberLevel::getMerchantNo, merchantNo);
        super.remove(wrapper);
        dto.getItems().forEach(x -> {
            save(merchantNo, x);
        });
        // 计算会员等级
        memberService.syncMemberLevel(merchantNo);
    }

    @Override
    public void save(long merchantNo, MemberLevelItemDto dto) {
        MemberLevel entity = new MemberLevel();
        entity.setId(IdUtil.generateLower());
        entity.setMerchantNo(merchantNo);
        entity.setName(dto.getName());
        entity.setStartIntegral(dto.getStartIntegral());
        entity.setEndIntegral(dto.getEndIntegral());
        entity.setDiscount(dto.getDiscount());
        entity.setColor(dto.getColor());
        super.save(entity);
    }

    @Override
    public List<MemberLevel> findAllByMerchantNo(long merchantNo) {
        Wrapper<MemberLevel> wrapper = new LambdaQueryWrapper<MemberLevel>()
                .eq(MemberLevel::getMerchantNo, merchantNo);
        return super.list(wrapper);
    }
}
